﻿using System;
using System.Diagnostics;
using System.Windows.Input;

namespace SSTU.ViewModel.Core
{
	public class ActionCommand : ICommand
	{
		#region Fields

		readonly Action _execute;
		readonly Func<bool> _canExecute;

		#endregion // Fields

		#region Constructors

		public ActionCommand(Action execute)
			: this(execute, null)
		{
		}

		public ActionCommand(Action execute, Func<bool> canExecute)
		{
			if (execute == null)
				throw new ArgumentNullException("execute");

			_execute = execute;
			_canExecute = canExecute;
		}
		#endregion // Constructors

		#region ICommand Members

		[DebuggerStepThrough]
		public bool CanExecute(object parameter)
		{
			return _canExecute == null ? true : _canExecute();
		}

		public event EventHandler CanExecuteChanged;

		public void Execute(object parameter)
		{
			_execute();
		}

		#endregion // ICommand Members

		public void RaiseCanExecuteChanged()
		{
			if (CanExecuteChanged != null)
			{
				CanExecuteChanged(this, new EventArgs());
			}
		}
	}
}
